<?php
require_once 'Zend/Controller/Action.php';
require_once 'MF/UserList.inc';

class Cms_UsersController extends Zend_Controller_Action {
    protected $_main;
    protected $_session;
    function init(){
		CmsAccess::restrictModule('users');
		
        $this->_main = MF_Main::getInstance();
        $this->_session = new Zend_Session_Namespace;        

        $this->view->setHelperPath('core/helpers/'); 
    }

    public function indexAction() {
		$order = $this->getOrder("login", "users");

		$filter = "";
		$this->view->f_login = "";

		if( isset($_POST['filtered']) ){
		  $this->_session->f_login = $_POST['f_login'];
		  $this->_session->f_email = $_POST['f_email'];
		  $this->_session->f_login_full = isset($_POST['f_login_full']);
		  $this->_session->f_email_full = isset($_POST['f_email_full']);
		}
		
		//в качестве индексов = key
		$users = MF_Main::getInstance()->UserList;
		$fNames = $users->getFlagNames(); //русские названия
		$fBits = $users->getFlagBits();   //номера битов
		
		$this->view->flagNames = $fNames;
		
		//фильтруем, если надо
        $this->view->f_login_full = ($this->_session->f_login_full)? 'checked': '';
		$this->view->f_email_full = ($this->_session->f_email_full)? 'checked': '';
		$this->view->filterCheck = 'checked';

		if( $this->_session->f_login ){
            if( $filter )
                $filter .= " and ";
            $f = ($this->view->f_login_full)? '': '%';
		    $filter .= " login like '$f".$this->_session->f_login."$f'";
		    $this->view->f_login = $this->_session->f_login;
		}
		  
		if( $this->_session->f_email ){
		    if( $filter )
		        $filter .= " and ";
            $f = ($this->view->f_login_full)? '': '%';		          
		    $filter .= " email like '$f".$this->_session->f_email."$f'";
		    $this->view->f_email = $this->_session->f_email;
		}

		if( $filter )
		  $filter = "where $filter";
		
		//получаем список пользователей
        $this->view->users = $this->_main->_sql->exe('select * from '.TAB_PREF.'user_list '.$filter.' order by '.$order);
    }	
	
    public function newsortAction(){
    	$filter = new Zend_Filter_StripTags();
        $table = $filter->filter($this->_getParam('table'));
        $field = $filter->filter($this->_getParam('field'));

        if( !isset($this->_session->order) ){//no order sets
            $this->_session->order = $table." ".$field." asc";
        }
        else{//orders sets is exist
            //parse current str
            $par = explode(" ", $this->_session->order);
            if( $par[0] == $table ){//table is old
                if( $par[1] == $field ){//field is old
                    if( $par[2] == "asc" ){//reverse order
                        $this->_session->order = $table." ".$field." desc";
                    }
                    else{
                        $this->_session->order = $table." ".$field." asc";
                    }
                }
                else{//new field
                    $this->_session->order = $table." ".$field." asc";
                }
            }
            else{//new table, new field, new order
                $this->_session->order = $table." ".$field." asc";
            }        
        }    
        $this->_redirect($_SERVER["HTTP_REFERER"]);  	
    }
    
    protected function getOrder($default, $table){
        
        //get order field
		//get sort columns
		$result = $default;
		if( isset($this->_session->order) ){
		  $par = explode(" ", $this->_session->order);
		  if( $par[0] == $table ){ //our table
    		  $this->view->sort_column = $par[1];
	       	  $this->view->sort_order = $par[2];
		  if( $this->view->sort_column != "" )
		      $result = $this->view->sort_column." ".$this->view->sort_order;	       	
		  }
		}   
		return $result; 
    }  

    
    function viewAction(){//редактировем пользователя    
      	$filter = new Zend_Filter_StripTags();

        $user_id = $filter->filter($this->_getParam('user_id'));

        //читаем данные по пользователю
        $user = MF_Main::getInstance()->UserList->getById($user_id);

        $this->view->user = $user;
        $this->view->user_data = array();
        $this->view->user_data['email'] = $user->email;
        $this->view->user_data['name'] = $user->name;
        /*$this->view->user_data['name_i'] = $user->name_i;
        $this->view->user_data['name_o'] = $user->name_o;
        $this->view->user_data['country'] = $user->country;
        $this->view->user_data['town'] = $user->town;
        $this->view->user_data['index'] = $user->index2;
        $this->view->user_data['street'] = $user->street;
        $this->view->user_data['house'] = $user->house;
        $this->view->user_data['korpus'] = $user->korpus;
        $this->view->user_data['flat'] = $user->flat;*/        
    }
    
    function addAction() {
    	if ($this->_request->isPost()) {
			$params = $this->_request->getPost();
			
			$user = MF_Main::getInstance()->UserList->addUser($params['login']);
			$user->password = $params['password'];
			$user->email = $params['email'];
			
			header('Location: /cms/users/edit/user_id/'.$user->user_id);
			return true;
		}
    }
    
    
    function editAction(){//редактировем пользователя
      	$filter = new Zend_Filter_StripTags();

        $user_id = $filter->filter($this->_getParam('user_id'));

        //читаем данные по пользователю
        $user_class = MF_Main::getInstance()->UserList;
        /*$search = $user_class->UserSearch();
        $search->login = $user_id;
        $users = $search->Make();*/
        $user = $user_class->getById($user_id);
        $this->view->user = $user;
        $f = true; //признак того, что все заполнили правильно
        $this->view->msg = '';

        $this->view->user_data = array();
        $this->view->user_data['email'] = $user->email;
        $this->view->user_data['phone'] = $user->phone;
        $this->view->user_data['name_f'] = $user->name_f;
        $this->view->user_data['name_i'] = $user->name_i;
        $this->view->user_data['name_o'] = $user->name_o;
        $this->view->user_data['country'] = $user->country;
        $this->view->user_data['town'] = $user->town;
        $this->view->user_data['index'] = $user->index2;
        $this->view->user_data['street'] = $user->street;
        $this->view->user_data['house'] = $user->house;
        $this->view->user_data['korpus'] = $user->korpus;
        $this->view->user_data['flat'] = $user->flat;

        if( isset($_POST['btn_save']) ){
//            $email = $filter->filter($_POST['email']);
            $this->view->err = array();
            //получаем все данные
            $email = $filter->filter($_POST['email']);
            $phone = $filter->filter($_POST['phone']);
            $name_f = $filter->filter($_POST['name_f']);
            $name_i = $filter->filter($_POST['name_i']);
            $name_o = $filter->filter($_POST['name_o']);
            $country = $filter->filter($_POST['country']);
            $town = $filter->filter($_POST['town']);
            $index = $filter->filter($_POST['index']);
            $street = $filter->filter($_POST['street']);
            $house = $filter->filter($_POST['house']);
            $korpus = $filter->filter($_POST['korpus']);
            $flat = $filter->filter($_POST['flat']);
            
            $this->view->user_data['email'] = $email;
            $this->view->user_data['phone'] = $phone;
            $this->view->user_data['name_f'] = $name_f;
            $this->view->user_data['name_i'] = $name_i;
            $this->view->user_data['name_o'] = $name_o;
            $this->view->user_data['country'] = $country;
            $this->view->user_data['town'] = $town;
            $this->view->user_data['index'] = $index;
            $this->view->user_data['street'] = $street;
            $this->view->user_data['house'] = $house;
            $this->view->user_data['korpus'] = $korpus;
            $this->view->user_data['flat'] = $flat;
                        
            
//            $pass = $filter->filter($_POST['password']);
            $f = true;
            
            //проверяем формат емайла            
            $validator = new Zend_Validate_EmailAddress();
            if (!$validator->isValid($email) ) {
                $this->view->err['wrong_email'] = 'Неправильный формат e-mail';
                $f = false; //заполнение не правильное
            } 

            //проверяем фио
            if( !$name_f ){
                $this->view->err['wrong_name_f'] = 'Укажите фамилию';
                $f = false;
            }
            
            if( !$name_i ){
                $this->view->err['wrong_name_i'] = 'Укажите имя';
                $f = false;
            }

            if( !$town ){
                $this->view->err['wrong_town'] = 'Укажите город';
                $f = false;
            }
            
            if( !$index ){
                $this->view->err['wrong_index'] = 'Укажите индекс';
                $f = false;
            }

            if( !$street ){
                $this->view->err['wrong_street'] = 'Укажите улицу';
                $f = false;
            }
            
            
            if( !$house ){
                $this->view->err['wrong_address'] = 'Укажите номер дома';
                $f = false;
            }
            
            if( $f ){ //все заполнено правильно, сохраняем в БД
                //сохраняем данные
                $user->email = $email;
                $user->phone = $phone;
                $user->name_f = $name_f;
                $user->name_i = $name_i;
                $user->name_o = $name_o;
                $user->country = $country;
                $user->town = $town;
                $user->index2 = $index;
                $user->street = $street;
                $user->house = $house;
                $user->korpus = $korpus;
                $user->flat = $flat;
                
                $this->view->msg = 'Данные сохранены';
            }
            else{
                $this->view->msg = 'В данных обнаруженая ошибка!';
            }
            $search->Make();
            $user = $search->item(0);
            $this->view->user = $user;
            
            
        }else{ //ничего не нажимали, просто выводим данные
        
        }
    }
    
    
	public function widgetAction() {
		CmsAuth::check();		
		
		$users = MF_Main::getInstance()->UserList;
		$userSearch = $users->UserSearch();

        if ((NULL !== $limit_from = $this->getRequest()->getParam('limit_from')) 
			&& (NULL !== $limit_amount = $this->getRequest()->getParam('limit_amount'))) {
				$userSearch->setLimits($limit_from,$limit_amount);
		}

        //берем фильтр        
        if( NULL !== $f_login = $this->getRequest()->getParam('f_login') ){
			 $userSearch->login = $f_login;
        }		

        if( NULL !== $f_email = $this->getRequest()->getParam('f_email') ){
			 $userSearch->email = $f_email;
        }	

        $val = "";
        if( NULL !== $f_status = $this->getRequest()->getParam('f_status') ){
            $val = $f_status[0]; //значение флажка
            $f_status = substr($f_status, 1, 100);
            $userSearch->flag->$f_status = $val;
        }	

//        echo $f_login."<br />";
//        echo $f_email."<br />";
//        echo $f_status." - ".$val;

        $userSearch->flag->system = 0; //системных пользователей показывать не надо
        
//        echo $userSearch->getSQL();
		$userSearch->Make();

		//формируем массив с данными
		$users_data = array();

		//в качестве индексов = key
		$fNames = $users->getFlagNames(); //русские названия
		$fBits = $users->getFlagBits();   //номера битов

		$this->view->flagNames = $fNames;

		for($i=0; $i<$userSearch->length(); $i++){
            $usersNote = $userSearch->item($i);
            //сформируем массив с флагами

            $usersNoteNode = 
                array(                                        
                    array('users_login',array('id' => $usersNote->user_id,'value' => $usersNote->login)),                    
                    array('users_email',array('id' => $usersNote->user_id,'value' => $usersNote->email))
                );		

            //пройдемся по флагам и, если выставлен, занести его в массив юзера
			foreach($fBits as $index => $c ){
                if( $index != 'system' ){ //этот флаг не нужен
                    $img_on = $this->getImgForStatus($index, true);
                    $img_off = $this->getImgForStatus($index, false);
                    
				    array_push($usersNoteNode, 
				        array('users_flags', 
				            array('id' => $usersNote->user_id, 'bit' => $index, 'value' => $usersNote->flag->$index, 'img_on' => $img_on, 'img_off' => $img_off)
				    ));
                }
			}
			array_push($usersNoteNode, array('users_pass',array('id' => $usersNote->user_id)));
			array_push($usersNoteNode, array('users_edit',array('id' => $usersNote->user_id)));
//			Zend_Debug::dump($usersNoteNode);            
            array_push($users_data, $usersNoteNode);                
		}
		
        $this->view->data = array('total_length' => $userSearch->total_length(), 'data' => $users_data);
        $this->renderScript('json.phtml');
	}
	
	/**
	 * получить имя картинки для статуса
	 *
	 * @param unknown_type $aStatusName
	 */
	protected function getImgForStatus($aStatusName, $aOn){
        switch ($aStatusName){
        case "is_vip": //иконка для випа
            return (($aOn)? "star.png": "star_empty.png");
            break;                        
        case 'blocked':
            return (($aOn)? "lock.png": "unlock.png");
            break;                        
        case 'checked':
            return (($aOn)? "flag_green.png": "flag_red.png");
            break;                        
            
        }	   
        
        
        return "";
	}

	public function changeAction() {
		CmsAuth::check();
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$user = MF_Main::getInstance()->UserList->getById($id);
		
		if (NULL !== $email = $this->getRequest()->getParam('email')) {
			$user->email = $email;
		}
		
		$this->view->result = '1';
		$this->_helper->layout->disableLayout(); 
	}

	
	public function flagAction(){

	   if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}

	   if (NULL === $flag = $this->getRequest()->getParam('flag')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		//опрокидываем указанный флаг
		$user = MF_Main::getInstance()->UserList->getById($id);
		
		$user->flag->$flag = $user->flag->$flag == '0' ? '1' : '0';
		$this->view->result = $user->flag->$flag;
		$this->_helper->layout->disableLayout(); 

		echo $this->getImgForStatus($flag, $user->flag->$flag == 1);//$user->flag->$flag;
	}
	
	public function checkloginAction() {
		$login = $this->getRequest()->getParam('login');
		$userList = MF_Main::getInstance()->UserList->UserSearch();
		$userList->login = $login;
		$userList->Make();
		echo $userList->length()==0 ? 'y' : 'n';
		$this->_helper->layout->disableLayout(); 
	}
	
	
	public function genpassAction(){
        $username = $this->getRequest()->getParam('id');
        $this->_helper->layout->disableLayout(); 
        echo substr(md5(rand(rand(5, 20), rand(30, 100)).$username), 3, 7);
	}
	
	public function passAction(){
      	$filter = new Zend_Filter_StripTags();

        $user_id = $filter->filter($this->_getParam('user_id'));

        $user_class = MF_Main::getInstance()->UserList;                
        $search = $user_class->UserSearch();
        $search->user_id = $user_id;
        $users = $search->Make();
        $user = $search->item(0);
        $this->view->user = $user;

        if( isset($_POST['btn_save']) ){
            $pass = $filter->filter($_POST['password']);
            if( $pass )
                $user->password = $pass;

            //отсылаем данные пользователю     
            if( isset($_POST['notification']) && $pass ){
                $mail = new Zend_Mail('win-1251');
                $mail->addTo($user->email, $user->login);
                $mail->setBodyText("
                    Ваши данные изменились:
                    Пароль: ".(($pass == "")? "Остался преждним": $pass));
                $mail->setSubject('Данные вашего аккаунта изменились');
                $mail->send();                
            }
            
            $this->view->msg = "Пароль сохранен";
        }
	}
	
}